// 用户信息接口 (查询, 修改)
const Router = require('koa-router')
const router = new Router();
const jwt = require("jsonwebtoken")
const { returnMsg, queryFn,jwtVerify } = require("../../config")
const bcrypt = require('bcryptjs')

router.get("/", async ctx => {

    // 获取 token, 前端请求头携带过来
    /* 
    ctx.request  请求   ctx.request.headers 请求头 ctx.requrest.body 请求体
    ctx.response 响应   ctx.respose.body 返回给前端的数据
     */

    // 绕开鉴权
    let token = ctx.request.headers['cms-token']
    if(!jwtVerify(token)){
        ctx.body = returnMsg(2, "查询用户失败","token已过期或该用户不存在")
        return;
    }
    let sql = `select username,token,avatar from user where token='${token}'`
    let result =  await queryFn(sql)
    ctx.body = returnMsg(1, "查询用户成功",result[0])
})

router.post("/", async ctx => {
    // 绕开鉴权
    let token = ctx.request.headers['cms-token']
    if(!jwtVerify(token)){
        ctx.body = returnMsg(2, "查询用户失败","token已过期或该用户不存在")
        return;
    }
    let {username, password} = ctx.request.body;
    if(!username || !password){
        ctx.body = returnMsg(1, "参数错误","用户名已存在")
        return
    }
    let sql5 = `select * from user where username='${username}'`
    let result5 =  await queryFn(sql5)
    if(result5.length > 0){
        ctx.body = returnMsg(1, "用户名已存在","用户名已存在")
        return
    }

    
    // let mmm = jwt.verify(token,"hanyu")
    let sql2 = `select username,token,avatar from user where token='${token}'`
    let result2 =  await queryFn(sql2)

    let sql = `update user set username = '${username || result2[0].username}',password = '${password || result2[0].password}' where token = '${token}'`
    let result =  await queryFn(sql)
    let sql1 = `select username,token,avatar from user where token='${token}'`
    let result1 =  await queryFn(sql1)
    ctx.body = returnMsg(0, "修改用户信息成功",result1)

})

module.exports = router;